package com.cotrino.feed2ereader;

import java.io.File;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.FileReader;
import java.util.List;
import java.util.Vector;
import yarfraw.utils.XMLUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;

/**
 * OpmlReader is a class to load OPML files.
 * 
 * @author      Jose Cotrino
 * @version     %I%, %G%
 * @since       1.0
 */
public class OpmlReader {

	Vector<String[]> list = null;

	/** 
	 * The constructor is actually doing the whole process,
	 * that is, reading the XML file and storing in a list for each feed:
	 * <ul>
	 * <li>Its title</li>
	 * <li>URL to the XML feed (RSS, Atom...)</li>
	 * <li>URL to the HTML content (required if image paths are relative)</li>
	 * </ul>
	 *
	 * @param opml		Path to the OPML file
	 * @return          <code>OpmlReader</code>
	 * @see				yarfraw.utils.XMLUtils
	 * @since           1.0
	 */
	public OpmlReader(String opml) {
		try {
			list = new Vector<String[]>();
			Element element = XMLUtils.parseXml(getFileContent(new File(opml)), false, false).getDocumentElement();
			NodeList feeds = element.getElementsByTagName("outline"); 
			for(int i=0; i<feeds.getLength(); i++) {
				Element feed = (Element)feeds.item(i);
				if( feed.getNodeType() == Node.ELEMENT_NODE && feed.hasAttribute("xmlUrl") ) {
					String[] feedArray = {
							feed.getAttribute("title"),
							feed.getAttribute("xmlUrl"),
							feed.getAttribute("htmlUrl")
					};
					list.add(feedArray);
				}
			}
		} catch (Exception e ) {
			System.err.println("OPML "+opml+" not found! "+e.getMessage());
			e.printStackTrace();
		}
	}
	
	/** 
	 * Read the content of a file and return it as a string
	 *
	 * @param file		File to be read
	 * @return          <code>String</code> with the content of the file
	 * @since           1.0
	 */
	public String getFileContent(File file) {
		StringBuilder contents = new StringBuilder();
		try {
			BufferedReader input =  new BufferedReader(new FileReader(file));
			try {
				String line = null;
				while(( line = input.readLine()) != null) {
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			} finally {
				input.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return contents.toString();
	}

	public List<String[]> getFeeds() {
		return list;
	}
}
